import ScorePanel from "./ScorePanel";
import Food from "./food";
import Snake from "./Snake";

class GameControl {
  food: Food
  scorePanel: ScorePanel
  snake: Snake
  direction: string;
  timer: any;
  isLive = false

  constructor() {
    this.food = new Food()
    this.scorePanel = new ScorePanel()
    this.snake = new Snake()
    this.direction = ''
    this.init()
  }
  init() {
    // js中this指向的是函数调用者
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.isLive = true
  }

  keydownHandler(e: KeyboardEvent) {
    if (e.key.search('Arrow') != -1)
      this.direction = e.key
    this.run()
  }

  run(): void {
    let X = this.snake.X
    let Y = this.snake.Y

    // 检测方向
    switch (this.direction) {
      case 'ArrowDown':
        Y += 10
        break;
      case 'ArrowUp':
        Y -= 10
        break;
      case 'ArrowLeft':
        X -= 10
        break;
      case 'ArrowRight':
        X += 10
        break;
      default:

        break;
    }

    clearTimeout(this.timer)
    this.checkIsEat()

    try {
      this.snake.X = X
      this.snake.Y = Y
    } catch (error: any) {
      /* 蛇撞墙游戏结束 */
      alert(error.message)
      this.isLive = false
    }

    this.isLive && (this.timer = setTimeout(() => {
      this.run()
    }, 300 - (this.scorePanel.level - 1) * 30))
  }

  checkIsEat() {
    if (this.food.X === this.snake.X && this.food.Y === this.snake.Y) {
      this.food.change()
      this.scorePanel.addScore()
      this.snake.addBody()
    }
  }
}



export default GameControl